/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package kingdoms;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTable;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.SerializationUtils;

/**
 *
 * @author ezequiel
 */
public class Ranking {

    List<Rank> ranks;

    public Ranking() {
        super();
        try {
            if (new File("ranking.king").exists()) {
                ranks = (List<Rank>) SerializationUtils.deserialize(new FileInputStream("ranking.king"));
            } else {
                ranks = new ArrayList();
            }
        } catch (Exception ex) {
            Logger.getLogger(Ranking.class.getName()).log(Level.SEVERE, null, ex);
            ranks = new ArrayList();
        }

    }

    public void adicionarRank(String jogador, int pontos) {
        boolean existe = false;
        for (Rank r : ranks) {
            if (r.getNome().equalsIgnoreCase(jogador)) {
                existe = true;
                if (r.getPontos() < pontos) {
                    r.setPontos(pontos);
                }
                break;
            }
        }

        if (!existe) {
            Rank r = new Rank(jogador, pontos);
            ranks.add(r);
        }

        salvarRanking();
    }

    private void salvarRanking() {
        try {
            FileUtils.writeByteArrayToFile(new File("ranking.king"), SerializationUtils.serialize((Serializable) ranks));
        } catch (IOException ex) {
            Logger.getLogger(Ranking.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public JTable getTabelaRanking() {
        String[] colunas = new String[]{"Posicao", "Nome", "Pontos"};

        String[][] dados = new String[ranks.size()][3];

        for (int i = 0; i < ranks.size(); i++) {
            dados[i][0] = String.valueOf(i);
            dados[i][1] = ranks.get(i).getNome();
            dados[i][2] = String.valueOf(ranks.get(i).getPontos());
        }

        JTable tabela = new JTable(dados, colunas);
        

        return tabela;
    }

}
